package com.hit.client.comm;

import cn.hutool.extra.spring.SpringUtil;
import com.hit.client.api.dto.config.RobotBaseProperties;
import com.hit.client.api.dto.config.RobotClientProperties;
import com.hit.comm.dto.CommWrapperDTO;
import com.hit.comm.dto.RegisterInfoReq;
import com.hit.comm.type.CommTypeEnum;
import com.hit.comm.utils.ProtostuffUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author kehanjiang
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<CommWrapperDTO> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ChannelCache.add(ctx);
        log.info("连接上服务端...");
        RobotClientProperties clientProperties = SpringUtil.getBean(RobotClientProperties.class);
        RobotBaseProperties baseInfo = clientProperties.getBaseInfo();
        if (baseInfo != null) {
            log.info("发送客户端注册信息...");
            CommWrapperDTO dto = new CommWrapperDTO();
            dto.setType(CommTypeEnum.TYPE_10000.getCode());
            RegisterInfoReq req = new RegisterInfoReq();
            BeanUtils.copyProperties(baseInfo, req);
            dto.setData(ProtostuffUtils.serialize(req));
            ctx.channel().writeAndFlush(dto);
        } else {
            log.error("无法注册客户端，请配置客户端信息！");
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        ChannelCache.remove(ctx);
        ctx.close();
        NettyClient.getInstance().connect(NettyClient.host, NettyClient.port);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, CommWrapperDTO commWrapperDTO) throws Exception {

    }
}
